let isEnabled = false;
let isSelecting = false;
let hoveredElement = null;
let selectedElement = null;

// 获取元素的XPath
function getXPath(element) {
    if (!element) return '';
    if (element.tagName.toLowerCase() === 'html') return '/html';

    let path = '';
    let current = element;

    while (current && current.nodeType === 1) {
        let index = 1;
        let hasFollowingSibling = false;

        // 计算同类型元素中的位置
        for (let sibling = current.previousSibling; sibling; sibling = sibling.previousSibling) {
            if (sibling.nodeType === 1 && sibling.tagName === current.tagName) {
                index++;
            }
        }

        // 检查是否需要添加索引
        for (let sibling = current.nextSibling; sibling && !hasFollowingSibling; sibling = sibling.nextSibling) {
            if (sibling.nodeType === 1 && sibling.tagName === current.tagName) {
                hasFollowingSibling = true;
            }
        }

        const tagName = current.tagName.toLowerCase();
        const pathIndex = (index > 1 || hasFollowingSibling) ? `[${index}]` : '';
        path = `/${tagName}${pathIndex}${path}`;

        current = current.parentNode;
    }

    return path;
}

// 复制文本到剪贴板
function copyToClipboard(text) {
    const textarea = document.createElement('textarea');
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
}

// 显示提示信息
function showNotification(message) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: #4CAF50;
        color: white;
        padding: 16px;
        border-radius: 4px;
        z-index: 10000;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    `;
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// 生成元素的树结构
function generateTreeStructure(element) {
    if (!element) return '';

    let html = '';

    // 处理元素节点
    if (element.nodeType === 1) {
        const tagName = element.tagName.toLowerCase();

        // 跳过不需要显示的标签
        if (['script', 'style', 'meta', 'link', 'noscript'].includes(tagName)) {
            return '';
        }
        // 跳过display:none的元素
        if (getComputedStyle(element).display === 'none') {
            return '';
        }

        const hasChildren = Array.from(element.children).some(child =>
            !['script', 'style', 'meta', 'link', 'noscript'].includes(child.tagName.toLowerCase())
        );
        const expandSymbol = hasChildren ? '▶' : '•';

        html += `<div class="tree-item" data-xpath="${getXPath(element)}">
            <span class="tree-expand">${expandSymbol}</span>
            <span class="tree-tag">&lt;${tagName}</span>`;

        // 添加属性
        const attributes = [];
        element.getAttributeNames().forEach(attr => {
            if (!['class'].includes(attr)) {
                const value = element.getAttribute(attr);
                if (value && attr === 'class') {
                    value = value.replace(/\s*xpath-finder-hover\s*/g, '');
                }
                if (value) {
                    attributes.push(`${attr}="${value}"`);
                }
            }
        });
        if (attributes.length > 0) {
            html += `<span class="tree-attr"> ${attributes.join(' ')}</span>`;
        }

        html += `<span class="tree-tag">&gt;</span>`;

        // 添加直接文本内容预览
        const textContent = Array.from(element.childNodes)
            .filter(node => node.nodeType === 3)
            .map(node => node.textContent.trim())
            .filter(text => text.length > 0)
            .join(' ');

        if (textContent) {
            const preview = textContent.length > 30 ? textContent.substring(0, 30) + '...' : textContent;
            html += `<span class="tree-text">${preview}</span>`;
        }

        // 处理子元素
        if (hasChildren) {
            html += '<div class="tree-indent" style="display: none;">';
            Array.from(element.children)
                .filter(child => !['script', 'style', 'meta', 'link'].includes(child.tagName.toLowerCase()))
                .forEach(child => {
                    html += generateTreeStructure(child);
                });
            html += '</div>';
        }

        // 添加闭合标签预览
        if (hasChildren || textContent) {
            html += `<span class="tree-tag">&lt;/${tagName}&gt;</span>`;
        }

        html += '</div>';
    }

    return html;
}

// 更新侧边栏预览内容
function updateSidebarPreview(element) {
    if (!element) return;

    // 移除临时添加的样式类，以免影响XPath生成
    const originalClass = element.className;
    element.classList.remove('xpath-finder-hover');

    const xpath = getXPath(element);

    // 获取HTML代码预览
    const htmlPreview = element.outerHTML;

    // 恢复样式类
    element.className = originalClass;

    chrome.runtime.sendMessage({
        type: 'updatePreview',
        xpath: xpath,
        text: element.innerText || '(无文本内容)',
        html: htmlPreview
    });
}

// 更新侧边栏树结构
function updateSidebarTree() {
    // 从html开始生成完整树结构
    const treeHtml = generateTreeStructure(document.documentElement);
    console.log('[Content] 更新树形结构');
    chrome.runtime.sendMessage({
        type: 'updateTree',
        treeHtml: treeHtml
    });
}

// 监听来自panel和background的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('[Content] 收到消息:', message);

    if (message.action === 'toggleXPathFinder') {
        setTimeout(updateSidebarTree, 100);
        cleanupSelection();
    } else if (message.type === 'toggleSelect') {
        isSelecting = message.enabled;
        if (isSelecting) {
            console.log('[Content] 开始选择元素');
            updateSidebarTree();
            document.addEventListener('mouseover', handleMouseMove, true);
            document.addEventListener('click', handleClick, true);
            document.body.style.cursor = 'crosshair';
        } else {
            document.removeEventListener('mouseover', handleMouseMove, true);
            document.removeEventListener('click', handleClick, true);
            document.body.style.cursor = 'default';

            if (hoveredElement && hoveredElement !== selectedElement) {
                hoveredElement.classList.remove('xpath-finder-hover');
                hoveredElement = null;
            }
        }
    } else if (message.type === 'selectTreeElement') {
        // 清除之前的选择
        if (selectedElement) {
            selectedElement.classList.remove('xpath-finder-hover');
        }
        if (hoveredElement && hoveredElement !== selectedElement) {
            hoveredElement.classList.remove('xpath-finder-hover');
        }

        // 通过XPath查找元素
        const element = document.evaluate(
            message.xpath, document, null,
            XPathResult.FIRST_ORDERED_NODE_TYPE, null
        ).singleNodeValue;

        if (element) {

            // 选中新元素，但不触发停止选择模式
            selectedElement = element;
            element.classList.add('xpath-finder-hover');

            // 滚动到元素位置
            element.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });

            // 更新预览信息，但移除临时样式类以免影响XPath生成
            const originalClass = element.className;
            element.classList.remove('xpath-finder-hover');
            const xpath = getXPath(element);
            element.className = originalClass;

            chrome.runtime.sendMessage({
                type: 'updatePreview',
                xpath: xpath,
                text: element.innerText || '(无文本内容)'
            });
        }
    } else if (message.type === 'requestTreeUpdate') {
        updateSidebarTree();
    }
});

// 停止选择模式
function stopSelection() {
    isSelecting = false;
    document.removeEventListener('mouseover', handleMouseMove, true);
    document.removeEventListener('click', handleClick, true);
    document.body.style.cursor = 'default';

    if (hoveredElement && hoveredElement !== selectedElement) {
        hoveredElement.classList.remove('xpath-finder-hover');
        hoveredElement = null;
    }

    // 通知面板更新按钮状态
    chrome.runtime.sendMessage({
        type: 'selectionStopped'
    });
}

// 选中元素（通过鼠标点击页面）
function selectElement(element) {
    if (!element || element === document.body) return;

    if (selectedElement) {
        selectedElement.classList.remove('xpath-finder-hover');
    }
    if (hoveredElement && hoveredElement !== element) {
        hoveredElement.classList.remove('xpath-finder-hover');
    }

    selectedElement = element;
    element.classList.add('xpath-finder-hover');

    // 添加事件监听器阻止冒泡
    element.addEventListener('click', (e) => {
        e.stopPropagation();
    }, true);

    updateSidebarPreview(element);
    stopSelection();
}

// 鼠标移动事件处理
function handleMouseMove(e) {
    if (!isSelecting) return;

    if (hoveredElement && hoveredElement !== selectedElement) {
        hoveredElement.classList.remove('xpath-finder-hover');
    }

    hoveredElement = e.target;
    if (hoveredElement === document.body) return;

    if (hoveredElement !== selectedElement) {
        hoveredElement.classList.add('xpath-finder-hover');
    }
    updateSidebarPreview(hoveredElement);

    e.stopPropagation();
}

// 鼠标点击事件处理
function handleClick(e) {
    if (!isSelecting) return;

    e.preventDefault();
    e.stopPropagation();

    // 确保点击的不是树形结构中的元素
    if (e.target.closest('.tree-item')) {
        return;
    }

    selectElement(e.target);
}

// 清理选择状态
function cleanupSelection() {
    isSelecting = false;
    document.removeEventListener('mouseover', handleMouseMove, true);
    document.removeEventListener('click', handleClick, true);
    document.body.style.cursor = 'default';
    if (hoveredElement) {
        hoveredElement.classList.remove('xpath-finder-hover');
        hoveredElement = null;
    }
    if (selectedElement) {
        selectedElement.classList.remove('xpath-finder-hover');
        selectedElement = null;
    }

    // 通知面板更新按钮状态
    chrome.runtime.sendMessage({
        type: 'selectionStopped'
    });
}
